import {GetLocation, ListDevicesOfLocation, UpdateDevice} from "~/lib/server";
import type {Route} from "./+types/location";
import {
    ActionButton,
    Button,
    Content,
    Dialog,
    DialogContainer,
    Divider,
    Flex,
    Form,
    Heading,
    ProgressCircle,
    TextField,
    useDialogContainer,
    View
} from '@adobe/react-spectrum';
import {useEffect, useState} from "react";
import {DestroyLocation} from "./location/delete";
import {EditLocation} from "./location/edit";
import {SelectLocation} from "~/ui/select-location";
import {DeviceCardBody} from "./device/card";
import {useQueryClient} from "@tanstack/react-query";

export default function Location({ params }: Route.ComponentProps) {
    const { data: location, error: locationErr, isLoading: locationIsLoading } = GetLocation(params.locationId);
    const {
        data: devices,
        error: devicesErr,
        isLoading: devicesIsLoading,
        mutate: refreshDevices
    } = ListDevicesOfLocation(params.locationId);

    return (
        <View padding="size-200">
            {locationIsLoading ? (
                <Flex justifyContent="center" marginY="size-300" width="100%">
                    <ProgressCircle aria-label="加载中..." size="L"/>
                </Flex>
            ) : locationErr ? (
                <View backgroundColor="negative" padding="size-200" marginY="size-200" borderRadius="medium">
                    <p className="text-white">加载位置信息失败</p>
                </View>
            ) : location && (
                <View marginBottom="size-300">
                    <Heading level={2} marginY="size-200">{location.name}</Heading>

                    {location.id > 0 && (
                        <Flex marginY="size-200" gap="size-100">
                            <EditLocation location={location} />
                            <DestroyLocation location={location} />
                        </Flex>
                    )}
                </View>
            )}

            <Divider size="S" marginY="size-300"/>

            {devicesIsLoading ? (
                <Flex justifyContent="center" marginY="size-300" width="100%">
                    <ProgressCircle aria-label="加载设备中..." size="L"/>
                </Flex>
            ) : devicesErr ? (
                <View backgroundColor="negative" padding="size-200" marginY="size-200" borderRadius="medium">
                    <p className="text-white">加载设备列表失败</p>
                </View>
            ) : !devices?.length ? (
                <View backgroundColor="informative" padding="size-200" marginY="size-200" borderRadius="medium">
                    <p className="text-white">暂无设备</p>
                </View>
            ) : (
                <View>
                    <Heading level={3} marginY="size-200">设备列表</Heading>
                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                        {devices.map((item) => (
                            <DeviceCard
                                device={item}
                                key={item.id}
                                onDeviceUpdated={() => refreshDevices()}
                            />
                        ))}
                    </div>
                </View>
            )}
        </View>
    );
}

function DeviceCard({device, onDeviceUpdated}: { device: Device, onDeviceUpdated: () => void }) {
    const [editDialog, setEditDialog] = useState(false);

    return (
        <div
            className="bg-white shadow-lg rounded-lg overflow-hidden hover:shadow-xl transition-all duration-300 border border-gray-100">
            <div className="p-5">
                <div className="flex items-center justify-between mb-3">
                    <ActionButton
                        isQuiet
                        onPress={() => setEditDialog(true)}
                        UNSAFE_className="text-left focus-ring-inside"
                    >
                        <span
                            className="text-xl font-medium text-gray-800 hover:text-blue-600 transition-colors">{device.name}</span>
                    </ActionButton>
                    <div className="bg-blue-50 rounded-full p-1.5">
                        <div className="h-2 w-2 rounded-full bg-blue-500"></div>
                    </div>
                </div>

                <div className="flex justify-between items-center mt-4">
                    <div className="bg-gray-50 px-4 py-3 rounded-xl">
                        <DeviceCardBody device={device}/>
                    </div>
                </div>
            </div>

            <DialogContainer onDismiss={() => setEditDialog(false)} isDismissable>
                {editDialog && (
                    <DeviceEditDialog
                        device={device}
                        onSuccess={() => {
                            setEditDialog(false);
                            onDeviceUpdated();
                        }}
                    />
                )}
            </DialogContainer>
        </div>
    );
}

function DeviceEditDialog({
                              device,
                              onSuccess
                          }: {
    device: Pick<Device, "name" | "locationId" | "id">,
    onSuccess: () => void
}) {
    const dialog = useDialogContainer();
    const queryClient = useQueryClient();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        console.log("设备编辑对话框打开，设备信息:", {
            id: device.id,
            name: device.name,
            locationId: device.locationId,
            locationIdType: typeof device.locationId
        });
    }, [device]);

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setIsSubmitting(true);
        setError(null);
        
        const formData = new FormData(e.currentTarget);
        const locationId = formData.get("locationId");

        console.log("表单数据：", Object.fromEntries(formData), "原始locationId:", locationId, "类型:", typeof locationId);

        // 确保我们正确处理formValue="key"设置
        // ComboBox使用formValue="key"时，提交的是选项的key值
        // 特别处理ID为0的情况
        let finalLocationId;
        if (locationId === "0") {
            console.log("检测到locationId为0");
            finalLocationId = 0;
        } else if (locationId) {
            finalLocationId = parseInt(locationId as string) || 0;
        } else {
            finalLocationId = device.locationId || 0;
        }
        
        const data = {
            name: formData.get("name") as string,
            locationId: finalLocationId,
        };

        console.log("最终提交的数据:", data);

        try {
            await UpdateDevice(device.id, data);
            // 更新缓存中的设备数据
            queryClient.invalidateQueries({queryKey: ["devices"]});
            onSuccess();
        } catch (error) {
            console.error("修改设备失败:", error);
            setError("修改设备失败，请重试");
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Dialog>
            <Heading>{device.name}</Heading>
            <Divider/>
            <Content>
                {error && (
                    <View backgroundColor="negative" padding="size-100" marginBottom="size-200" borderRadius="medium">
                        <p className="text-white">{error}</p>
                    </View>
                )}
                
                <Form onSubmit={onSubmit}>
                    <TextField name="name" label="设备名称" defaultValue={device.name} />
                    <SelectLocation defaultSelectedKey={device.locationId}/>

                    <Flex marginTop="size-200" gap="size-100">
                        <Button
                            variant="accent"
                            type="submit"
                            isDisabled={isSubmitting}
                        >
                            {isSubmitting ? "修改中..." : "修改"}
                        </Button>
                        <Button
                            variant="secondary"
                            onPress={() => dialog.dismiss()}
                        >
                            取消
                        </Button>
                    </Flex>
                </Form>
            </Content>
        </Dialog>
    );
}

